<template>
  <div>
    <!-- 顶部标题 -->
    <div class="title-infomation">
      <el-row>
        <el-col :span="12"><h2>成绩管理</h2></el-col>
        <el-col :span="12">
          <div class="top-right-info">
            <!-- 选择学期 -->
            <el-form :inline="true">
              <el-form-item label="当前学期为">
                <el-select v-model="selectSemId" :placeholder="nowSemster.semName" @change="selectOtherSemester()">
                  <el-option
                    v-for="item in allSemesterInfo"
                    :key="item.semId"
                    :label="item.semName"
                    :value="item.semId"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 条件搜索 -->
    <div class="top-infomation">
      <el-row v-if="loading === false">
        <div class="addUser">
          <div class="top-button-info">
            <el-button type="primary" @click="addUserScore()">发布成绩</el-button>
          </div>
          <div class="top-button-info">
            <el-button type="primary" @click="sendExcel()">成绩导出</el-button>
          </div>
          <div class="top-button-info">
            <el-button type="primary" @click="saveFile()">活动保存</el-button>
          </div>
        </div>
      </el-row>
      <!-- 搜索按钮 -->
    </div>
    <!-- 中间内容 -->
    <el-table
      id="excel-table"
      v-loading="loading"
      :data="userInfo"
      stripe
      highlight-current-row
      class="table-all-info"
    >
      <el-table-column
        prop="userId"
        label="工号"
        align="center"
        fixed
        width="150"
      />
      <el-table-column
        label="用户信息"
        align="center"
      >

        <el-table-column
          prop="userName"
          label="姓名"
          align="center"
          width="100"
        />
        <el-table-column
          prop="branch.branchName"
          label="党小组"
          align="center"
          width="150"
        />
      </el-table-column>
      <el-table-column label="分数信息" align="center">
        <el-table-column label="当前分数" align="center" width="100">
          <template v-if="scope.row.totalInfo" slot-scope="scope">
            {{ (scope.row.totalInfo.sendScore === null) ? 0 : (scope.row.totalInfo.sendScore &lt; -500 ) ? '一票否决' : scope.row.totalInfo.sendScore }}
          </template>
        </el-table-column>
        <el-table-column label="分数状态" align="center" width="100">
          <template v-if="scope.row.totalInfo" slot-scope="scope">
            <el-tag :type="`${scope.row.totalInfo.sendStatus === '未发布'?'info':'success'}`">{{ scope.row.totalInfo.sendStatus }}</el-tag>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="评分细则" align="center">
        <!-- 一级标题 -->
        <template v-for="(flist,flistIndex) in routerInfo">
          <el-table-column :key="flistIndex" :label="`${flist.name}(${flist.maxScore === 99999 ? '一票否决':flist.maxScore})`" align="center">
            <!-- 二级标题 -->
            <template v-for="(slist,slistIndex) in flist.child">
              <el-table-column :key="slistIndex" :label="`${slist.name}(${slist.maxScore === 99999 ? '一票否决' : slist.maxScore})`" align="center" width="110">
                <!-- 三级标题 -->
                <template v-if="slist.child.length !== 0">
                  <template v-for="(tlist,tlistIndex) in slist.child">
                    <el-table-column :key="tlistIndex" :label="`${tlist.name}(${tlist.maxScore === 99999 ? '一票否决':tlist.maxScore})`" align="center" width="110">
                      <template v-if="scope.row.send" slot-scope="scope">
                        {{ `${scope.row.send.find(item=>item.sendFlistId === flist.id&&item.sendSlistId === slist.id&&item.sendTlistId === tlist.id) === undefined ? 0 :scope.row.send.find(item=>item.sendFlistId === flist.id&&item.sendSlistId === slist.id&&item.sendTlistId === tlist.id).sendScore === -999?'一票否决':scope.row.send.find(item=>item.sendFlistId === flist.id&&item.sendSlistId === slist.id&&item.sendTlistId === tlist.id).sendScore}` }}
                      </template>
                    </el-table-column>
                  </template>
                </template>
                <template v-if="scope.row.send" slot-scope="scope">
                  {{ `${scope.row.send.find(item=>item.sendFlistId === flist.id&&item.sendSlistId === slist.id) === undefined ? 0 :scope.row.send.find(item=>item.sendFlistId === flist.id).sendScore === -999?'一票否决':scope.row.send.find(item=>item.sendFlistId === flist.id).sendScore }` }}
                </template>
              </el-table-column>
            </template>
          </el-table-column>

        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { getSemester, getAllSemester } from '../../api/semester.js'
import { getAllInfo, getAllRouter, getAllUserInfo } from '../../api/user.js'
import { forUserGetSend } from '../../api/send.js'
import { getallUserScoreBySemId, pushScore, getAllTotal } from '../../api/total.js'
import { getZipBySemName } from '../../api/flie.js'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  data() {
    return {
      userInfo: [], // 用户信息数据
      nowSemster: {}, // 当前学期全部信息
      nowSemId: '', // 当前学期
      excelStatus: true,
      // 全部学期信息存储位置
      allSemesterInfo: [],
      selectSemId: '', // 选择的semId
      loading: true,
      routerInfo: []
    }
  },
  created() {
    // 获取学期信息
    this.getShowSemester()
    // 获取全部学期信息
    this.getAllSemesterInfo()
    // 获取全部路由信息
    this.getAllRouterInfo()
  },
  methods: {
    // 全部调用方法
    // 获取学期信息
    getShowSemester() {
      var that = this
      var semId = sessionStorage.getItem('semId')
      new Promise(function(resolve, reject) {
        if (semId === '无开放学期') {
        // 设置默认为第一个学期
          that.getSemesterInfo('1')
          semId = '1'
          that.nowSemId = '1'
          resolve()
        } else {
          that.nowSemId = semId
          that.getSemesterInfo(semId)
          resolve()
        }
      }).then(() => {
        // 根据登录权限获取所有用户信息
        that.getAllUserInfo()
      })
    },
    // 根据登录权限获取所有用户信息
    getAllUserInfo() {
      getAllUserInfo().then((res) => {
        // 获取当前权限
        const userType = sessionStorage.getItem('user_Type')
        let userInfo = []
        // 如果是党小组权限 只能查看党小组信息
        if (userType === '6') {
          getAllInfo(sessionStorage.getItem('userId')).then((data) => {
            const userBranch = data.obj.userinfo.userBranch
            for (const i in res.obj) {
              if (res.obj[i].userinfo.userBranch === userBranch) {
                userInfo.push(res.obj[i].userinfo)
              }
            }
          })
        } else {
          userInfo = res.obj.map((item) => (item.userinfo))
        }
        // 根据用户名称，查找用户信息
        this.getUserInfoSend(userInfo)
      })
    },
    // 获取全部路由信息
    getAllRouterInfo() {
      getAllRouter().then((res) => {
        const routerInfo = []
        for (const i in res.obj) {
          if (res.obj[i].flist.flistPath !== '/publicMark') {
            continue
          } else {
            const flist = {}
            // 添加一级标题信息
            flist.id = res.obj[i].flist.flistId
            flist.name = res.obj[i].flist.flistName
            flist.maxScore = res.obj[i].flist.flistMaxScore
            flist.minScore = res.obj[i].flist.flistMinScore
            flist.child = []
            // 如果存在二级标题
            if (res.obj[i].slists.length === 0) {
              routerInfo.push(flist)
              continue
            } else {
              for (const j in res.obj[i].slists) {
                const slist = {}
                slist.id = res.obj[i].slists[j].slist.slistId
                slist.name = res.obj[i].slists[j].slist.slistName
                slist.maxScore = res.obj[i].slists[j].slist.slistMaxScore
                slist.minScore = res.obj[i].slists[j].slist.slistMinScore
                slist.child = []
                // 判断当前二级标题是否有三级标题
                if (res.obj[i].slists[j].tlist.length === 0) {
                  flist.child.push(slist)
                  continue
                } else {
                  for (let x = 0; x < res.obj[i].slists[j].tlist.length; x++) {
                    const tlist = {}
                    tlist.id = res.obj[i].slists[j].tlist[x].tlistId
                    tlist.name = res.obj[i].slists[j].tlist[x].tlistName
                    tlist.maxScore = res.obj[i].slists[j].tlist[x].tlistMaxScore
                    tlist.minScore = res.obj[i].slists[j].tlist[x].tlistMinScore
                    slist.child.push(tlist)
                  }
                  flist.child.push(slist)
                }
              }
              routerInfo.push(flist)
            }
          }
        }
        this.routerInfo = routerInfo
      })
    },
    // 获取send表中的用户信息
    getUserInfoSend(userInfo) {
      var that = this
      new Promise((resolve) => {
        getAllTotal().then((data) => {
          userInfo.map(async(item, index) => {
            const totalInfo = data.obj.find(total => total.totalSemId === +this.nowSemId && total.totalUserId === item.userId)
            if (totalInfo) item.totalScore = totalInfo.totalScore
            const { obj: send } = await forUserGetSend(that.nowSemId, item.userId)
            const sendScoreMap = send ? send.map((item) => item.sendScore ? item.sendScore : 0) : []
            const sendScore = sendScoreMap.length > 0 ? sendScoreMap.reduce((pre, cur) => pre + cur) : 0
            userInfo[index] = {
              ...item,
              send,
              totalInfo: {
                sendScore,
                totalScore: item.totalScore ? item.totalScore : 0,
                sendStatus: sendScore === item.totalScore ? '已发布' : '未发布'
              }
            }
            if (sendScore !== item.totalScore) {
              this.excelStatus = false
            }
            if (index === userInfo.length - 1) {
              resolve()
            }
          })
        })
      }).then(() => {
        setTimeout(() => {
          that.userInfo = userInfo
          that.loading = false
        }, 500)
      })

      // new Promise((resolve, reject) => {
      //   for (let i = 0; i < userInfo.length; i++) {
      //     forUserGetSend(that.nowSemId, userInfo[i].userId).then((res) => {
      //       userInfo[i].send = res.obj || []
      //     })
      //     if (i === userInfo.length - 1) {
      //       resolve()
      //     }
      //   }
      // }).then(() => {
      //   // 获取成绩信息
      //   setTimeout(() => {
      //     this.getUserScore(userInfo)
      //   }, 500)
      // })
    },
    // 获取成绩信息
    getUserScore(userInfo) {
      var that = this
      getallUserScoreBySemId(this.nowSemId).then((res) => {
        for (let i = 0; i < userInfo.length; i++) {
          for (let j = 0; j < res.obj.length; j++) {
            if (userInfo[i].userId === res.obj[j].userId) {
              const total = {
                sendScore: res.obj[j].sendScore,
                totalScore: res.obj[j].totalScore === null ? 0 : res.obj[j].totalScore,
                sendStatus: ''
              }
              if (res.obj[j].sendScore === res.obj[j].totalScore) {
                total.sendStatus = '已发布'
              } else {
                that.excelStatus = false
                total.sendStatus = '未发布'
              }
              userInfo[i].totalInfo = total
              break
            }
          }
          if (i === userInfo.length - 1) {
            that.userInfo = userInfo
            that.loading = false
          }
        }
      })
    },
    // 发布成绩
    addUserScore() {
      var that = this
      var userInfo = that.userInfo
      var semId = that.nowSemId
      //   信息提醒
      this.$confirm('您将使用发布成绩功能，发布后所有党员可查看成绩。发布成绩后，如需复核修改，请再修改完成后，再次点击发布成绩功能。点击确定可发布成绩，点击取消则取消发布。', '请注意：', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (that.excelStatus !== true) {
          for (let i = 0; i < userInfo.length; i++) {
            pushScore(semId, userInfo[i].userId, userInfo[i].totalInfo.sendScore).then((res) => {
              if (res.msg !== '操作成功') {
                this.$message({
                  type: 'info',
                  message: '服务器异常'
                })
              }
              if (i === userInfo.length - 1) {
                this.$message({
                  type: 'success',
                  message: '发布成功'
                })
                that.loading = true
                that.excelStatus = true
                that.getShowSemester()
              }
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          this.$message({
            type: 'success',
            message: '发布成功'
          })
        }
      }).catch((err) => {
        console.log(err)
        that.show = false
        this.$message({
          type: 'info',
          message: '已取消发布'
        })
      })
    },
    // 成绩导出
    sendExcel() {
      const excelName = '党员微积分-' + this.nowSemster.semName + '学期用户信息成绩表.xlsx'
      const fix = document.querySelector('.el-table__fixed')
      if (this.excelStatus === false) {
        this.$message({
          type: 'info',
          message: '请发布成绩后再导出'
        })
      } else {
        let wb
        if (fix) { // 判断要导出的节点中是否有fixed的表格，如果有，转换excel时先将该dom移除，然后append回去
          wb = XLSX.utils.table_to_book(document.querySelector('#excel-table').removeChild(fix))
          document.querySelector('#excel-table').appendChild(fix)
        } else {
          wb = XLSX.utils.table_to_book(document.querySelector('#excel-table'))
        }
        const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
        try {
          FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), excelName)
        } catch (e) {
          if (typeof console !== 'undefined') console.log(e, wbout)
        }
        return wbout
      }
    },
    // 保存活动
    saveFile() {
      var that = this
      if (this.excelStatus === false) {
        this.$message({
          type: 'info',
          message: '请发布成绩后再导出'
        })
      } else {
        getZipBySemName(that.nowSemster.semName).then(res => {
          if (res.result === true) {
            window.location.href = res.msg
            this.$message({
              type: 'success',
              message: '文件下载成功'
            })
          } else if (res.result === false) {
            this.$message({
              type: 'warning',
              message: res.msg
            })
          } else {
            this.$message({
              type: 'warning',
              message: '系统繁忙请联系管理员'
            })
          }
        })
      }
    },
    // 获取全部学期的方法
    getAllSemesterInfo() {
      var that = this
      getAllSemester().then((res) => {
        that.allSemesterInfo = res.obj
      })
    },
    // 获取学期信息
    getSemesterInfo(semId) {
      var that = this
      getSemester(semId).then((res) => {
        that.nowSemster = res.obj
      })
    },
    // 选择其他学期
    selectOtherSemester() {
      this.$message({
        type: 'info',
        message: '请等待，正在更新中'
      })
      this.nowSemId = this.selectSemId
      this.getSemesterInfo(this.nowSemId)
      this.getAllUserInfo()
    }
  }
}
</script>
<style lang="scss" scoped>
.title-infomation{
  margin-top:3rem;
  margin-left: 4rem;
}
.top-right-info{
  float: right;
  margin-right: 8rem;
  margin-top: 0.83em;
}
.table-all-info{
  width: 90%;
  margin: 0 auto;
  margin-bottom: 2rem;
}
.top-infomation{
  margin:2rem 0 3rem 7rem;
}
.addUser{
  display: flex;
}
.top-button-info{
  margin-right: 1rem;
}
</style>
